package com.eckey.lab.service.impl;

import com.alibaba.fastjson.JSON;
import com.eckey.lab.bean.AccountFreezeTbl;
import com.eckey.lab.dao.AccountFreezeTblDao;
import com.eckey.lab.dao.UserDao;
import com.eckey.lab.entity.User;
import com.eckey.lab.enums.UserState;
import com.eckey.lab.service.TCCUserService;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.BusinessActionContextParameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;

/**
 * @Author: Marinc
 * @CreateTime: 2023-12-13  09:51
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Service
public class TCCUserServiceImpl implements TCCUserService {

    @Resource
    private AccountFreezeTblDao accountFreezeTblDao;

    @Resource
    private UserDao userDao;

    @Transactional
    public void deduct(Integer userId, int money) {
        String xid = RootContext.getXID();
        User user = userDao.queryById(userId);
        if (user == null) {
            log.error("userId不存在");
            throw new RuntimeException("userId不存在");
        }
        if (user.getRemainingSum() - money >= 0) {
            user.setRemainingSum(user.getRemainingSum() - money);
        }
        userDao.update(user);
        AccountFreezeTbl accountFreezeTbl = new AccountFreezeTbl();
        accountFreezeTbl.setUserId(userId.toString());
        accountFreezeTbl.setFreezeMoney(String.valueOf(money));
        accountFreezeTbl.setXid(xid);
        accountFreezeTbl.setState(UserState.TRY.getValue());
        accountFreezeTblDao.insert(accountFreezeTbl);
        log.info("插入数据成功：{}", JSON.toJSONString(accountFreezeTbl));

    }


    public boolean confirm(BusinessActionContext businessActionContext) {
        String xid = businessActionContext.getXid();
        int count = accountFreezeTblDao.deleteById(xid);
        return count == 1;
    }


    public boolean cancel(BusinessActionContext businessActionContext) {
        String xid = businessActionContext.getXid();
        AccountFreezeTbl accountFreezeTbl = accountFreezeTblDao.queryById(xid);
        //1.空回滚的判断，判断freeze是否为null，为null证明try没执行，需要进行空回滚


        //2.恢复可用余额
        String userId = accountFreezeTbl.getUserId();
        User user = userDao.queryById(Integer.valueOf(userId));
        user.setRemainingSum(user.getRemainingSum() + Integer.valueOf(accountFreezeTbl.getFreezeMoney()));
        userDao.update(user);

        //3.将冻结金额清零，状态改为Cancel
        accountFreezeTbl.setFreezeMoney(String.valueOf(0));
        accountFreezeTbl.setState(UserState.CANCEL.getValue());

        accountFreezeTblDao.update(accountFreezeTbl);
        return false;

    }


}
